import paramiko
import time
from openpyxl import load_workbook
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor


def config(ip,user,passwd,company,hostnames):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=ip,port=22,username=user,password=passwd)
    print(hostnames + " 连接成功！")
    ssh_clinet = ssh.invoke_shell()
    #判断设备厂家
    if company == "Huawei":
        ssh_clinet.send('screen-length 0 temporary\n')
    if company == "H3C":
        ssh_clinet.send('screen-length disable\n')
    if company == "Huawei_DC":
        ssh_clinet.send('N\n')
        ssh_clinet.send('screen-length 0 temporary\n')
    
    ssh_clinet.send('display current-configuration \n')
    print("获取到配置，请稍等")
    time.sleep(15)
    conf = ssh_clinet.recv(999999)
    ssh_clinet.close()
    now_time = datetime.now()
    f = open("D:/git/Zhangqiuxian/python/交换机自动配置/text/" + str(now_time.year) + "-" + str(now_time.month) + "-" + str(now_time.day) + " " + hostnames + " " + ip + ".txt", "a+b")
    f.write(conf)
    time.sleep(1)
    f.close()



if __name__ == '__main__':
    wb = load_workbook('host.xlsx')
    ws = wb['Switch']

    # 2.创建线程池(数量可以自己调整)
    pool = ThreadPoolExecutor(ws.max_row)
    start_time = time.time()

    for info in range(1, ws.max_row):
        hostname = ws.cell(info + 1, 1).value
        ip = ws.cell(info + 1, 2).value
        username = ws.cell(info + 1, 3).value
        passwd = ws.cell(info + 1, 4).value
        company = ws.cell(info + 1, 5).value
        pool.submit(config,ip,username,passwd,company,hostname)
    pool.shutdown(wait=True)
    end_time = time.time()
    print(f"一共用时: {end_time - start_time}")